<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * DateTime: 18-9-7下午3:28
 */

namespace ThirdPartyAuthorizeBundle\thirdPartyAuthorize\common;


class StringTool
{
    /**
     * 验证码类型字母
     */
    const RANDOM_CAPTCHA = 1;

    /**
     * 验证码类型字母
     */
    const RANDOM_NUMBER = 2;

    /**
     * 处理短文本中的表情进行处理
     *
     * @param $content
     * @param bool $is_saved 是否保存到表情到数据库，是则对其进行base64_encode编码, 否则过滤掉表情
     * @return mixed
     */
    public static function encodeContentWithEmoticon($content, $is_saved = false)
    {
        if( $is_saved ) {
            $content = preg_replace('~<img(.*?)>~s','',$content);
            return preg_replace_callback('/[\xf0-\xf7].{3}/', function ($r) {
                return '@E' . base64_encode($r[0]);
            }, $content);
        }

        $content = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $content
        );

        return $content;

    }

    /**
     * 产生随机码(默认长度为4)[可选]
     *
     * @param $type  RANDOM_CAPTCHA|RANDOM_NUMBER
     * @param $length
     * @return string
     */
    public static function generateRandom($type, $length)
    {
        $chars = '';
        if ($type === self::RANDOM_CAPTCHA) {
            $chars = 'abcdefghijklmnpqrstuvwxyzABCDEFGHJKLMNPQEST0123456789';
        } else if ($type === self::RANDOM_NUMBER) {
            $chars = '0123456789';
        }

        $randomStr = '';
        $len = strlen($chars);
        for ($i=0; $i < $length; $i++){
            $randomStr .= $chars[rand(0,$len-1)];
        }

        return $randomStr;
    }
}